cc.Class({
    extends: cc.Component,

    properties: {
        labelWidthMax: 0,

        _label: cc.Label,
        _labelString: 0,
        _myChangedString: false,
    },

    editor: {
        menu: 'ExtendUI/LabelClampEX',
        requireComponent: cc.Label,
    },

    // use this for initialization
    onLoad: function () {
        this._label = this.getComponent(cc.Label);
        this.init();
        this._onSizeChanged();
    },

    init: function() {
        this._label.overflow = cc.Label.Overflow.NONE;
        this._labelString = this._label.string;
        this._label.string = '...';
        this.labelWidthMax -= this.node.width;
        this._label.string = this._labelString;
        this.node.on('size-changed', this._onSizeChanged, this);
    },

    _onSizeChanged: function() {
        if (this._myChangedString === true) {
            return;
        }
        if (this.node.width <= this.labelWidthMax) {
            return;
        }
        for (var i = 0; i < this._label.string.length; i++) {
            this.setLabelString(this._label.string.substring(0, this._label.string.length - 1));
            if (this.node.width <= this.labelWidthMax) {
                this.setLabelString(this._label.string + '...');
                return;
            }
        }
    },

    setLabelString: function(str) {
        this._myChangedString = true;
        this._label.string = str;
        this._myChangedString = false;
    }
});
